package com.example.freeengine.filetranslate.fragment.receive.listadapter;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import com.example.freeengine.R;
import com.example.freeengine.filetranslate.FileTranslateViewModel;
import com.example.freeengine.filetranslate.persistence.entity.FileTranslateProgress;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutionException;

public class FileTranslateReceiveListAdapter extends ListAdapter<FileTranslateProgress, FileTranslateReceiveListAdapter.MyViewHolder> {

    private static final String TAG = FileTranslateReceiveListAdapter.class.getSimpleName();

    Context context;
    FileTranslateViewModel viewModel;

    static DiffUtil.ItemCallback DIFFCALLBACK = new DiffUtil.ItemCallback<FileTranslateProgress>() {
        @Override
        public boolean areItemsTheSame(@NonNull @NotNull FileTranslateProgress oldItem, @NonNull @NotNull FileTranslateProgress newItem) {
            return oldItem.getId().equals(newItem.getId());
        }

        @Override
        public boolean areContentsTheSame(@NonNull @NotNull FileTranslateProgress oldItem, @NonNull @NotNull FileTranslateProgress newItem) {
            return oldItem.equals(newItem);
        }
    };

    public FileTranslateReceiveListAdapter() {
        super(DIFFCALLBACK);
    }

    public FileTranslateReceiveListAdapter(Context context) {
        super(DIFFCALLBACK);
        this.context = context;
    }
    public FileTranslateReceiveListAdapter(Context context, FileTranslateViewModel viewModel) {
        super(DIFFCALLBACK);
        this.context = context;
        this.viewModel = viewModel;
    }

    @NonNull
    @NotNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        return new MyViewHolder(layoutInflater.inflate(R.layout.filetanslate_receive_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull MyViewHolder holder, int position) {

        FileTranslateProgress data = getItem(position);

        holder.tvFileName.setText(data.getName());
        holder.tvProgressNumber.setText(data.getProgress() + "%");
        holder.pbFileTranslate.setProgress(data.getProgress());

        if (data.getStatus() == 0){
            holder.ivMenu.setVisibility(View.INVISIBLE);
        }else {
            holder.ivMenu.setVisibility(View.VISIBLE);
            holder.ivMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PopupMenu popup = new PopupMenu(context, v);
                    MenuInflater inflater = popup.getMenuInflater();
                    inflater.inflate(R.menu.menu_filetranslate_receive_list_item, popup.getMenu());
                    popup.show();

                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {

                            switch (item.getItemId()){
                                case R.id.filetranslate_receive_list_item_menu_backup: {

                                    String fileMimeType = viewModel.getFileMimeType(data.getFilePath());
                                    Log.i(TAG, "mime type: " + fileMimeType);
                                    File file = new File(data.getFilePath());
                                    if (!file.exists()){
                                        Toast.makeText(context, "文件已删除", Toast.LENGTH_SHORT).show();
                                        return true;
                                    }
                                    ContentValues contentValues = new ContentValues();
                                    contentValues.put("title", data.getName());
                                    contentValues.put("_display_name", data.getName());
                                    contentValues.put("mime_type", fileMimeType);
                                    Uri insert = context.getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);

                                    try(OutputStream outputStream = context.getContentResolver().openOutputStream(insert);
                                        InputStream inputStream = new FileInputStream(file)){
                                        byte[] b = new byte[1024];
                                        int len;
                                        while ((len = inputStream.read(b)) > 0){
                                            outputStream.write(b, 0, len);
                                        }
                                        Toast.makeText(context, "文件已保存到Documents", Toast.LENGTH_SHORT).show();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    return true;
                                }
                                case R.id.filetranslate_receive_list_item_menu_delete:{

                                    new AlertDialog.Builder(context)
                                            .setTitle("提示")
                                            .setMessage("是否删除该文件?" + "\n" + data.getName())
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    try {
                                                        viewModel.getFileTranslateRepository().delete(data);
                                                        File file = new File(data.getFilePath());

                                                        if (file.exists()){
                                                            boolean delete = file.delete();
                                                        }
                                                        file.deleteOnExit();

                                                    } catch (ExecutionException | InterruptedException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            })
                                            .show();


                                    return true;
                                }
                                default:
                                    return false;
                            }
                        }
                    });
                }
            });

        }

    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tvFileName, tvProgressNumber;
        ProgressBar pbFileTranslate;
        ImageView ivMenu;

        public MyViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            tvFileName = itemView.findViewById(R.id.filetranslate_receive_list_item_filename);
            tvProgressNumber = itemView.findViewById(R.id.filetranslate_receive_list_item_progress_number);
            pbFileTranslate = itemView.findViewById(R.id.filetranslate_receive_list_item_progressbar);
            ivMenu = itemView.findViewById(R.id.filetranslate_receive_list_item_menu);
        }
    }

}
